const user = require("../databases/user")
const jwt = require("jsonwebtoken");
const md5 = require("md5")

module.exports = (req,res,next)=>{
  const { token, uId, opassword, npassword } = req.body;
  if(!npassword){
    res.send({
      code:4,
      msg:"缺少必传参数：npasswrod"
    })
    return
  }
  jwt.verify(token, "千锋H5", async (err, tokenData)=>{
    if(err){
      res.send({
        code:0,
        msg:"登录失效，或未登录"
      })
    }else{
      if(tokenData.uId === uId || !uId){
        if(!opassword){
          res.send({
            code:4,
            msg:"缺少必传参数：opasswrod"
          })
          return
        }
        const userData = await user.find({
          uId: tokenData.uId,
          password: md5(opassword)
        })
        if(userData.length > 0){
          await user.updateOne({uId: tokenData.uId}, {
            password: md5(npassword)
          })
          res.send({
            code:1,
            msg:"修改自己密码成功"
          })
        }else{
          res.send({
            code:3,
            msg:"老密码不对"
          })
        }
      }else if(tokenData.power == 2){
        await user.updateOne({uId}, {
          password: md5(npassword)
        });
        res.send({
          code:1,
          msg:"修改别人密码成功"
        })
      }else{
        res.send({
          code:2,
          msg:"权限不够"
        })
      }
    }
  })
}
